package com.guxiaotu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

/**
 * 注册阿里的Druid的数据源
 * @author Gu Yuanhua
 * created time 2018/8/4 14:42
 */
@Configuration
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {

    private final Environment env;

    public DataSourceConfig(Environment env) {
        this.env = env;
    }

    /**
     * 生产环境
     */
    @Bean("dataSource")
    @Profile("prod")
    public DataSource dataSourceProd() {
        return getDataSource (env, "prod.url");
    }

    /**
     * 测试环境
     */
    @Bean("dataSource")
    @Profile("dev")
    public DataSource dataSourceDev() {
        return getDataSource (env, "dev.url");
    }

    private static DataSource getDataSource(Environment env, String url) {
        DruidDataSource dataSource = new DruidDataSource ();
        dataSource.setDriverClassName (env.getProperty ("driver"));
        dataSource.setUrl (env.getProperty (url));
        dataSource.setUsername (env.getProperty ("user"));
        dataSource.setPassword (env.getProperty ("password"));
        return dataSource;
    }

}
